package biz.datalk.industrialland.common.encrypt;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

/**
 *
 * HmacSHA1
 * HmacSha256
 * HmacSha512
 *
 *
 * @author tarofang@163.com
 * @date 2020-11-30
 */
public class HmacShaTool {
    // KkW00VJyoj0mJeZ2
    private static final String DEFAULT_KEY = "KkW00VJyoj0mJeZ2";

    public static String hmacSha256(String plaintext, String key) throws Exception {
        Mac hmacSHA256 = Mac.getInstance("HmacSHA256");
        SecretKeySpec secret_key = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), "HmacSHA256");
        hmacSHA256.init(secret_key);
        byte[] array = hmacSHA256.doFinal(plaintext.getBytes(StandardCharsets.UTF_8));

        StringBuilder sb = new StringBuilder();
        for (byte item : array) {
            sb.append(Integer.toHexString((item & 0xFF) | 0x100), 1, 3);
        }

        return sb.toString().toLowerCase();
    }

    public static String hmacSha256(String plaintext) throws Exception {
        return hmacSha256(plaintext, DEFAULT_KEY);
    }

    public static void main(String[] args) {
        try {
            String ue = "yanglei@datalk.biz";
            String un = "yanglei@datalk.biz";
            String key = "KkW00VJyoj0mJeZ2";
            // key = "YAzCgckTQwOmmvQo";

            String res = hmacSha256(ue + un, key);

            // 10e847cd91ca87d2232db7f821d6bfe860a3a21f9948a70549d6bc5fb3130da8
            // 40abc6919262655c54aab0701be64a0fbe8abc6f95fac00765eed398418727c0
            System.out.println(res);
            System.out.println("");

            String enUe = URLEncoder.encode(ue, StandardCharsets.UTF_8.name());
            // enUe = ue;
            String enUn = URLEncoder.encode(un, StandardCharsets.UTF_8.name());
            // enUn = un;
            String url = "http://cloudfile.im.cdcyy.cn/3rdpartsso/verify?ue=" + enUe + "&un=" + enUn + "&sig=" + res;
            System.out.println(url);
            System.out.println("");

        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}
